//
//  RegisterPageViewController.m
//  SchoolTimetable
//
//  Created by 梦里都是梦 on 16/1/8.
//  Copyright © 2016年 Yuanlinqian. All rights reserved.
//

#import "RegisterPageViewController.h"
#import "Tools.h"
#import "RootTabBarController.h"
#import "PersonPageViewController.h"
#import "LoginPageViewController.h"

@interface RegisterPageViewController ()
@property (weak, nonatomic) IBOutlet UITextField *userNameTF;
@property (weak, nonatomic) IBOutlet UITextField *passwordTF;
@property (weak, nonatomic) IBOutlet UITextField *emailTF;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTF;
// 获取验证码Btn
@property (weak, nonatomic) IBOutlet UIButton *getCodeBtn;
// 输入验证码textField
@property (weak, nonatomic) IBOutlet UITextField *verifyCodeTF;
// 保存注册用户名
@property(nonatomic,copy) NSString * registerUserName;

@end

@implementation RegisterPageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backBarButtonItemPredded:)];

}
-(void)backBarButtonItemPredded:(UIBarButtonItem *)sender
{
    [AnimationTool setAnimationWith:kCATransitionPush and:kCATransitionFromLeft andTime:0.7 with:self];
    [self.navigationController popViewControllerAnimated:NO];
}
- (IBAction)getCodeBtnPressed:(UIButton *)sender {
    if (self.phoneNumberTF.text.length == 0) {
        return;
    }
    __block int timeout= 60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [sender setTitle:@"获取验证码" forState:UIControlStateNormal];
                sender.enabled = YES;
            });
        }else{
            //            int minutes = timeout / 60;
            //            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                
                [sender setTitle:[NSString stringWithFormat:@"%@秒再次获取",strTime] forState:UIControlStateNormal];
                sender.enabled = NO;
                
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
    [BmobSMS requestSMSCodeInBackgroundWithPhoneNumber:self.phoneNumberTF.text andTemplate:@"test" resultBlock:^(int number, NSError *error) {
        if (error == nil) {
            [SVProgressHUD showSuccessWithStatus:@"短信已发送,请注意查收"];
        }
        else{
            [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
        }
        sender.enabled = YES;
    }];

}
- (IBAction)registerBtnPressed:(UIButton *)sender {
    if (self.verifyCodeTF.text.length == 0) {
        return;
    }

    [BmobSMS verifySMSCodeInBackgroundWithPhoneNumber:self.phoneNumberTF.text andSMSCode:self.verifyCodeTF.text resultBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            BmobUser *bUser = [[BmobUser alloc] init];
            bUser.username = self.userNameTF.text;
            bUser.mobilePhoneNumber = self.phoneNumberTF.text;
            NSString * pwdMD5Str = [Tools MD5StringFromString:self.passwordTF.text];
            [bUser setObject:@(YES) forKey:@"mobilePhoneNumberVerified"];
            
            [bUser setPassword:pwdMD5Str];
            if (self.emailTF.text.length >0 ) {
            bUser.email = self.emailTF.text;
            }


            [bUser signUpInBackgroundWithBlock:^ (BOOL isSuc, NSError *err){
                if (isSuc){
                    [SVProgressHUD showSuccessWithStatus:@"注册成功"];
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [[NSNotificationCenter defaultCenter]postNotificationName:USER_REFRESH_USERINFO object:nil];
                        [AnimationTool setAnimationWith:kCATransitionPush and:kCATransitionFromLeft andTime:0.7 with:self];
                        [self.navigationController popViewControllerAnimated:NO];
                    });
                    
                    
                    
                    
                    
                } else {
                    [SVProgressHUD showErrorWithStatus:[err localizedDescription]];
                }
            }];

        }
        else{
            [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
        }
    }];

   
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
